<template>
  <div class="expiring-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>即将过期药材</span>
          <div>
            <el-button type="primary" @click="loadData">刷新</el-button>
            <el-button @click="exportData">导出</el-button>
          </div>
        </div>
      </template>

      <el-alert
          title="即将过期药材说明"
          description="以下药材即将过期，请及时处理"
          type="error"
          show-icon
          style="margin-bottom: 20px;"
      />

      <div class="filter-section" style="margin-bottom: 20px;">
        <el-radio-group v-model="daysFilter" @change="handleFilterChange">
          <el-radio-button :label="7">7天内过期</el-radio-button>
          <el-radio-button :label="30">30天内过期</el-radio-button>
          <el-radio-button :label="0">全部</el-radio-button>
        </el-radio-group>
      </div>

      <el-table
          :data="filteredExpiringList"
          v-loading="loading"
          stripe
          style="width: 100%"
      >
        <el-table-column prop="herbName" label="药材名称" width="150" />
        <el-table-column prop="batchNumber" label="批次号" width="120" />
        <el-table-column prop="quantity" label="当前库存(g)" width="100" align="center">
          <template #default="{ row }">
            {{ row.quantity }}
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100" align="center">
          <template #default="{ row }">
            ￥{{ row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="storageLocation" label="存储位置" width="120" />
        <el-table-column prop="purchaseDate" label="采购日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.purchaseDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="过期日期" width="120">
          <template #default="{ row }">
            <span :class="getExpirationDateClass(row.expirationDate)">
              {{ formatDate(row.expirationDate) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="daysUntilExpiry" label="剩余天数" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getExpiryTagType(row.daysUntilExpiry)">
              {{ row.daysUntilExpiry }}天
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120" />
        <el-table-column prop="qualityNotes" label="质量备注" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isAvailable ? 'success' : 'danger'">
              {{ row.isAvailable ? '可用' : '不可用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" link @click="handleDispose(row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="empty-state" v-if="!loading && filteredExpiringList.length === 0">
        <el-empty description="暂无即将过期药材数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { herbInventoryApi } from '@/api/admin'

const router = useRouter()
const loading = ref(false)
const expiringList = ref([])
const daysFilter = ref(30) // 默认显示30天内过期的

// 加载即将过期数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await herbInventoryApi.getExpiringList()
    expiringList.value = res.data || []
    ElMessage.success(`加载完成，共 ${expiringList.value.length} 条即将过期记录`)
  } catch (error) {
    ElMessage.error('加载即将过期数据失败')
    console.error('加载即将过期数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 过滤显示的数据
const filteredExpiringList = computed(() => {
  if (daysFilter.value === 0) {
    return expiringList.value
  }
  return expiringList.value.filter(item =>
      item.daysUntilExpiry <= daysFilter.value && item.daysUntilExpiry >= 0
  )
})

const exportData = () => {
  // 实现导出功能
  ElMessage.info('导出功能开发中...')
}

const handleFilterChange = () => {
  // 过滤条件改变时自动重新计算
}

const handleEdit = (row) => {
  router.push(`/admin/herb-inventory/edit/${row.inventoryId}`)
}

const handleDispose = (row) => {
  ElMessageBox.confirm(
      `确定要处理药材"${row.herbName}"吗？`,
      '处理药材',
      {
        confirmButtonText: '确认处理',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    ElMessage.success('处理成功（功能开发中）')
  }).catch(() => {
    // 用户取消操作
  })
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

const getExpiryTagType = (days) => {
  if (days < 0) return 'danger'
  if (days <= 7) return 'danger'
  if (days <= 30) return 'warning'
  return 'success'
}

const getExpirationDateClass = (date) => {
  if (!date) return ''
  const expirationDate = new Date(date)
  const today = new Date()
  const diffTime = expirationDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays < 0) return 'expired'
  if (diffDays <= 7) return 'expiring-soon'
  return ''
}

// 页面挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.expiring-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.filter-section {
  display: flex;
  justify-content: flex-start;
}

.expired {
  color: #f56c6c;
  font-weight: bold;
}

.expiring-soon {
  color: #e6a23c;
  font-weight: bold;
}
</style>
